#include "serviceserver.h"

#include "serviceclient.h"


ServiceServer::ServiceServer(int port, QObject *parent) : Server(port, parent)
{
}


void ServiceServer::connectClient(){
    ServiceClient *client = new ServiceClient(p_tcpServer->nextPendingConnection(), this);
    qDebug() << "HttpClient connected";
    //connect(client, SIGNAL(requestReceived(HttpRequest)), this, SLOT(processRequest(HttpRequest)));
    v_clientList.append(client);
    connect(client, SIGNAL(dataReceived(QByteArray)), this, SLOT(broadcast(QByteArray)));
}


void ServiceServer::disconnectClient()
{
    qDebug() << "httpClient disconnected";
}


void ServiceServer::broadcast(QByteArray data){
    QByteArray toSend;
    int dataCount = data.count();
    toSend.append(129);
    if(dataCount <= 125)
       toSend.append((char)data.count());
    else if(dataCount <= 0xFFFF)
    {
        toSend.append(126);
        toSend.append((dataCount & 0xFF00) >> 8);
        toSend.append(dataCount & 0xFF);
    }
    toSend += data;
    for(int i=0; i<v_clientList.count(); i++){
        v_clientList.at(i)->send(toSend);
    }
}
